package com.vdongchina.thread.base.demo;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * 等待/通知的具体实践
 *
 *  只能在同步代码块里使用
 *
 *  synchronized (obj){
 *                         obj.wait();
 *                     }
 *
 *  synchronized (obj){
 *             obj.notify();
 *         }
 *
 *  在原有的基础上,添加了到期时间机制,及规定时间内没有被唤醒也会停止等待返回结果,避免了资源被占满的危险
 */
public class WaitNotify {



    static volatile boolean flag = true;
    static Object lock = new Object();  //申明一个静态当一个锁的对象


    public static void main(String[] args) {
        Thread waitThread = new Thread(new Wait(), "WaitThread");
        waitThread.start();
        SleepUtils.second(5);
        Thread notifyThread = new Thread(new Notify(), "NotifyThread");
        notifyThread.start();
    }


    /**
     * 这里是改造的地方
     */
    static class Wait implements Runnable {
        @Override
        public void run() {
            synchronized (lock) {
                //等待3秒,没有收到通知,及也返回
                long future = System.currentTimeMillis()+3000;
                long remaining = 3000;
                while (flag && remaining > 0) {  //判断条件, 1是被通知,及有结果返回, 2是3秒时间到了,自动返回
                    System.out.println("循环----");
                    try {
                        System.out.println(Thread.currentThread() + " flag is true.  @ " + new SimpleDateFormat("HH:mm:ss").format(new Date()));
                        //整个线程进入wait状态,循环停止,wait会释放锁
                        //如果不通知会导致线程堵塞,那么这里使用等待超时模式
                        lock.wait(remaining);
                        remaining = future-System.currentTimeMillis();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                System.out.println(Thread.currentThread() + " flag is false. running @" + new SimpleDateFormat("HH:mm:ss").format(new Date()));
            }
        }
    }

    static class Notify implements Runnable {

        @Override
        public void run() {
            synchronized (lock) {
                System.out.println(Thread.currentThread() + " flag is true " + new SimpleDateFormat("HH:mm:ss").format(new Date()));
                lock.notifyAll(); //通知不会释放锁,线程进入到block状态
                flag = false;
                SleepUtils.second(5);
            }

            synchronized (lock) {
                System.out.println(Thread.currentThread() + " hold lock again. sleep @ " + new SimpleDateFormat("HH:mm:ss").format(new Date()));
                SleepUtils.second(5);
            }

        }
    }

    static class SleepUtils {
        public static void second(int i) {
            try {
                TimeUnit.SECONDS.sleep(i);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

    }


}
